package com.wuxin.ssm.controller;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageInfo;
import com.wuxin.ssm.entity.*;
import com.wuxin.ssm.mapper.OrderdetailMapper;
import com.wuxin.ssm.service.*;
import com.wuxin.ssm.util.AlipayConfig;
import com.wuxin.ssm.vo.ForeProductInfoVo;
import com.wuxin.ssm.vo.ProductInfoVo;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: untitled
 * @ClassName ForeProductInfoController
 * @description:
 * @author: 李尧坤
 * @create: 2024−12-17 19:12
 * @Version 1.0
 **/
@Controller
@RequestMapping("/fore")
public class ForeProductInfoController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private CarShopService carShopService;

    @Autowired
    private AddressService addressServicce;

    @Autowired
    private XmorderService xmorderService;

    @Autowired
    private ProductTypeService productTypeService;

    //每页显示5条属性
    public  static  final int PAGE_SIZE=4;

    //  /fore/detailOne.action?pid=1

    @RequestMapping("/detailOne.action")
    public String detailOne(Integer pid, HttpSession session){
        //根据id 查询商品详情
        ProductInfo productInfo =  productInfoService.findProductById(pid);
        // 存储一下
        session.setAttribute("prod",productInfo);

        return "redirect:/productdetail.jsp";
    }

    //  /fore/carShop.action?pid=1
    @RequestMapping("/carShop.action")
    public String addCarShop(Integer pid,HttpSession session){
        //获取当前登录的用户信息
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }

        Carshop carshop = new Carshop();
        carshop.setUid(user.getUid());
        carshop.setPid(pid);

        // 检查购物车中是否已存在该物品
        Carshop oldCarshop = carShopService.findByUidAndPid(carshop);
        if (oldCarshop != null) {
            // 如果存在，合并数量
            oldCarshop.setNumbers(oldCarshop.getNumbers() + 1);
            carShopService.updateCarShop(oldCarshop);
        } else {
            // 如果不存在，添加新记录
            carshop.setNumbers(1);
            carShopService.save(carshop);
        }

        return "redirect:showCarshop.action";
    }


    /**
     * 购物车信息展示
     * @param session
     * @return
     */
    @RequestMapping("/showCarshop.action")
    public String showCarshop(HttpSession session){
        //获取当前登录用户信息
        Users user = (Users) session.getAttribute("user");

        List<Carshop> carshopList = carShopService.getAllCarShopByUserId(user.getUid());

        session.setAttribute("carlist",carshopList);

        return "redirect:/carshop.jsp";
    }

    //
    @RequestMapping("/changeNumber.action")
    private String updateCarShop(Integer cid,Integer num){
        Carshop carshop = new Carshop();
        carshop.setCid(cid);
        carshop.setNumbers(num);

        carShopService.updateCarShop(carshop);
        return "redirect:showCarshop.action";
    }



    //${(pageContext.request.contextPath)}/fore/delete.action?cid=${car.cid}
    @RequestMapping("/delete.action")
    public String deleteCarShop(Integer cid){
        carShopService.deleteById(cid);
        return "redirect:showCarshop.action";
    }

    //http://localhost:8080/ssm_war_exploded/fore/showOrder.action
    @RequestMapping("showOrder.action")
    public String showOrder(HttpSession session){
        //获取当前登录用户信息
        Users user = (Users) session.getAttribute("user");
        System.out.println(user.getUid());
        //获取订单
        List<Xmorder> xmorderList = xmorderService.selectOrder(user.getUid());

        System.out.println();

        session.setAttribute("orderList",xmorderList);
        return "redirect:/myorder.jsp";
    }

    //    <a href="${pageContext.request.contextPath}/fore/logout.action">注销</a>
    @RequestMapping("/logout.action")
    public String logout(HttpSession session) {
        // 清除 Model 中的登录信息
        session.invalidate();
        // 重定向到登录页面
        return "redirect:/myindex.jsp";
    }











    //    ${pageContext.request.contextPath}/prod/mainServlet
    @RequestMapping("/mainServlet.action")
    public String mainServlet(HttpSession session, ForeProductInfoVo foreProductInfoVo, Integer page, Model model) {

        //获取全部的商品类型
        List<ProductType> typeList = productTypeService.getAll();
        //将数据都存入session
        session.setAttribute("typeList",typeList);

        //声明一个p代表页码
        Integer p = 1;

        if (page != null) {
            p=page;
        }
        if (page == null) {
            page = p;
        }

        //多条件组合查询
        PageInfo prodList = productInfoService.Forechaxun(page,PAGE_SIZE,foreProductInfoVo);

        //存储一下
        session.setAttribute("prodList",prodList);

        session.setAttribute("foreProductInfoVo",foreProductInfoVo);

        // /admin/product.jsp

        return "redirect:/allproduct.jsp";
    }













    //     /fore/showAddress.action
    @RequestMapping("showAddress.action")
    public String showAddress(HttpSession session){
        //获取当前登录用户的信息
        Users user = (Users) session.getAttribute("user");  //jwt
        //一个人有多个地址
        List<Address> list = addressServicce.findAddressByid(user.getUid());

        session.setAttribute("addressList",list);

        return "redirect:/jiesuan.jsp";

    }

        //  /fore/zhifu.action
    @RequestMapping("/zhifu.action")
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    public void zhifu(HttpServletRequest request, HttpServletResponse response){
        //地址可能新增
        //订单表添加数据
        //订单明细表添加多条数据
        //扣减库存
        //使用事务

        //获取当前登录用户的信息
        Users user = (Users) request.getSession().getAttribute("user");
        //购物车从session中拿到
        List<Carshop>  carshopList  = (List<Carshop>)request.getSession().getAttribute("carlist");
        //创建地址对象
        Address address  = new Address();

        //设置地址id
        Integer aid = -1;

        System.out.println();
        //获取用户选择的商品
        String[] pids = request.getParameterValues("pid");

        String showadd = request.getParameter("showadd");

        if (showadd != null) {
            //复选框被选中了 想要新增地址

            String cnee =request.getParameter("cnee");
            String phone =request.getParameter("phone");
            String newaddress =request.getParameter("newaddress");


            System.out.println(user.getUid());
            address.setUid(user.getUid());
            address.setCnee(cnee);
            address.setAddress(newaddress);
            address.setPhone(phone);

            //新的地址存入数据库
            addressServicce.insertAddress(address);

            aid = address.getAddressid();
            System.out.println("generatedId："+aid);
        } else {
            aid =Integer.parseInt(request.getParameter("rdo")) ;
        }

        //处理订单
        Xmorder xmorder = new Xmorder();
        //订单所有者
        xmorder.setUid(user.getUid());
        xmorder.setAddressid(aid);
        xmorder.setStatus("未支付");
        //总金额
        double total = Double.parseDouble(request.getParameter("total"));
        xmorder.setTotalprice(total);
        xmorder.setOdate(new Date());
        xmorder.setRemarks("赶快支付，否则取消订单");
        //订单编号

        String oid = UUID.randomUUID().toString().replace("-","").substring(0,11);
        //java.util.UUID
        xmorder.setOid(oid);




        //添加订单
        int num  = xmorderService.save(xmorder,pids,carshopList);



        if (num > 0) {

            //清空购物车
            for (String pid:pids){
                carShopService.deleteById2(Integer.valueOf((pid)),user.getUid());
            }

            //添加订单成功，准备进行支付
            response.setContentType("text/html;charset=UTF-8");

            //初始化 请求参数  {"name":"wuxin","age":18}
            AlipayClient alipayClient =
                    new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                            AlipayConfig.app_id,
                            AlipayConfig.merchant_private_key,
                            "JSON",AlipayConfig.charset,
                            AlipayConfig.alipay_public_key,AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            // 服务器异步通知页面路径
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
            // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
            alipayRequest.setReturnUrl(AlipayConfig.return_url);

            //设置参数
            String subject="小米商城的订单支付";
            String out_trade_no=oid;
            Double total_amount=total;



            alipayRequest.setBizContent("{" +
                    "    \"out_trade_no\":\""+oid+"\"," +
                    "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                    "    \"total_amount\":"+total+"," +
                    "    \"subject\":\""+subject+"\"," +
                    "    \"body\":\""+subject+"\"," +
                    "    \"timeout_express\":\"90m\"" +"}");

            //请求
            String result="";



            try{
                result=alipayClient.pageExecute(alipayRequest).getBody();

                response.setContentType("text/html;charset="+AlipayConfig.charset);
                //将结果输出到 页面上
                response.getWriter().write(result);
                response.getWriter().flush();
                response.getWriter().close();



            }catch(Exception ex){
                ex.printStackTrace();
            }

        }


    }
}
